package com.liuguoqing.framework.context.support;

import com.liuguoqing.framework.beans.BeanDefinition;
import com.liuguoqing.framework.beans.factory.support.BeanDefinitionReader;
import com.liuguoqing.framework.beans.factory.support.BeanDefinitionRegistry;
import com.liuguoqing.framework.context.ApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author : liugq
 * @Date : 2022/7/19 23:42
 * @See : 参考类
 * @Since： JDK1.8
 * @Version : 1.0
 */
public abstract class AbstractApplicationContext implements ApplicationContext {
    protected BeanDefinitionReader beanDefinitionReader;
    //用来存储bean对象的容器   key存储的是bean的id值，value存储的是bean对象
    protected Map<String, Object> singletonObjects = new HashMap<String, Object>();

    //存储配置文件的路径
    protected String configLocation;

    /**
     * 进行配置文件加载并进行对象创建
     */
    @Override
    public void refresh() throws IllegalStateException, Exception {
        //加载BeanDefinition
        beanDefinitionReader.loadBeanDefinitions(configLocation);

        //初始化bean
        finishBeanInitialization();
    }

    /**
     * bean的初始化,使用了模板方法模式，  getBean方法就是给子类实现
     */
    private void finishBeanInitialization() throws Exception {
        BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
        String[] beanNames = registry.getBeanDefinitionNames();

        for (String beanName : beanNames) {
            //BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
            //调用getBean方法，可以完成所有bean的获取，同时将bean注册成功
            getBean(beanName);
        }
    }

}
